with Logging;

package body NAL_Analyzer is

   -- buffpackage body NAL_Analyzer is

   -- buffer TS packet = 188 bytes
   -- buffer PES packet = 2**16
   -- start array at -1 so look back 2 bytes without checking
   -- for out of bounds

   procedure Read(NAL: out Byte_Buffer_Type; InFile : in IO.File_Type) is
      I : Positive := 3; -- so we can look back safely
      Current : IO.Byte_Type;
      use type Stream_IO.Positive_Count;
   begin
      -- init NAL buffer
      NAL.Byte_Buffer(1) := 1;
      NAL.Byte_Buffer(2) := 1;
      NAL.Start_Pos := 1;
      NAL.Size := 0;

      while (not Stream_IO.End_Of_File(InFile.File)) loop
         Byte_Type'Read(InFile.File_Access, Current);
         NAL.Byte_Buffer(I) := Current;

         if NAL.Byte_Buffer(I) = 1 and NAL.Byte_Buffer(I-1) = 0 and NAL.Byte_Buffer(I-2) = 0 then
            if NAL.Start_Pos = 1 then
               NAL.Start_Pos := I-2; -- found start of NAL
            --elsif NAL.Byte_Buffer(I-3) = 0 then
            --   NAL.NAL_End := I-4; -- remove tailing 0
            --   NAL_Found;
            else
               NAL.Size := (I-2) - NAL.Start_Pos;
               -- move back file pointer
               Stream_IO.Set_Index(InFile.File, Stream_IO.Index(InFile.File) - 3);
               Logging.Info("Found NAL length: " & Integer'Image( NAL.Size ));
               Logging.Info("File index: " & Stream_IO.Positive_Count'Image(Stream_IO.Index(InFile.File) ));
               return;
            end if;
         end if;
         I := I + 1;
      end loop;

      -- return the last nal
      if NAL.Start_Pos > 1 then
         NAL.Size := I - NAL.Start_Pos;
      end if;

   end Read;



end NAL_Analyzer;
